package com.code.xugu;

import cn.hutool.json.JSONUtil;
import com.xugu.cloudjdbc.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * <p>
 *
 * </p>
 *
 * @author chw
 * @date 2025/4/1
 */
public class XuGuDb {
    private static final Logger logger = LoggerFactory.getLogger(XuGuDb.class);
    private String user = "app_test";
    private String password = "Qwz3bEAP3D+2yoDf";
    private String className = "com.xugu.cloudjdbc.Driver";
    private String url = "jdbc:xugu://203.195.146.38:5138/TPM?current_schema=app_test&useUnicode=true&characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";

    public static void main(String[] args) throws SQLException {
        XuGuDb xuGuDb = new XuGuDb();
        xuGuDb.test();
    }

    public void test() throws SQLException {
        Connection conn = getConnection();
        //设置事务为非自动提交模式
        try {
            conn.setAutoCommit(false);
            //创建数据库Statement对象
            Statement stm = conn.createStatement();
            //数据库事务执行SQL语句
            String sql = "insert into T_AUTO (name,age) values('李四',18)";
            stm.execute(sql);
            String sql2 = "insert into T_AUTO_INFO (name,age) values('小李四',13)";
            //执行静态SQL语句
            stm.execute(sql2);
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            //事务回滚方法
            conn.rollback();
        }
    }

    public Connection getConnection() throws SQLException {
        Connection con = null;
        try {
            Class.forName(className);
            logger.info("加载数据库驱动成功！");
            con = (Connection) DriverManager.getConnection(url, user, password);
            logger.info("创建数据库连接成功！【{}】", JSONUtil.toJsonPrettyStr(con));
        } catch (Exception e) {
            logger.info("创建数据库连接失败！");
            con = null;
            e.printStackTrace();
        } finally {
            if (con != null) {
                //释放连接资源
                con.close();
            }
        }
        return con;
    }
}
